package org.spbsu.squaddie.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.spbsu.squaddie.model.Cell;
import org.spbsu.squaddie.model.Event;
import org.spbsu.squaddie.model.Pair;

public class Utils {
	public static Double getAverage(Event event) {
		if (event.size() % 2 != 0) {
			System.out.println("Not odd.");
			return null;
		}

		Integer center = event.size() / 2 - 1;

		Cell left = event.get(center);
		Cell right = event.get(center + 1);

		return getAverage(left, right);
	}

	public static Double getAverage(Cell left, Cell right) {
		Double oddDifference = right.getFirst() - left.getFirst();
		Double depthSum = left.getSecond() + right.getSecond();

		return left.getFirst() + oddDifference * left.getSecond() / depthSum;
	}

	public static Pair<Cell, Cell> parseLine(String input) {
		String[] lines = input.split(" ");

		Double leftOdd = Double.parseDouble(lines[3]);
		Double rightOdd = Double.parseDouble(lines[4]);
		Double leftDepth = Double.parseDouble(lines[21]);
		Double rightDepth = Double.parseDouble(lines[22]);

		// for (String line : lines) {
		// System.out.println(line);
		// }

		return new Pair<Cell, Cell>(new Cell(leftOdd, leftDepth), new Cell(
				rightOdd, rightDepth));
	}

	public static Double getOdd(String input, int i) {
		String[] lines = input.split(" ");

		return Double.parseDouble(lines[i]);
	}

	public static void saveSerie(String filename, List<Double> averages) {

		File file = new File(filename);

		if (file.exists()) {
			file.delete();
		}

		PrintWriter printWriter = null;
		try {
			printWriter = new PrintWriter(file);
			for (Double value : averages) {
				printWriter.println(value.toString());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (printWriter != null) {
				printWriter.close();
			}
		}

	}

	public static List<Double> thinList(List<Double> input,
			Integer dilutionFactor) {
		List<Double> output = new ArrayList<>();

		for (int i = 0; i < input.size(); ++i) {
			if (i % dilutionFactor == 0) {
				output.add(input.get(i));
			}
		}

		return output;
	}

	public static Double getArithmeticAverage(List<Double> input) {
		Double sum = 0.0;

		for (int i = 0; i < input.size(); ++i) {
			sum += input.get(i);
		}

		return sum / input.size();
	}
}
